package javamobile.billsplit;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javamobile.utils.MySocket;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class PayBillActivity extends Activity {

	public static final String PREFS_NAME = "MyPrefsFile";
    
    @SuppressWarnings("unchecked")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.pay_bill);
        
        // Get bill ID
        Intent intent = getIntent(); 
        int billID= intent.getIntExtra("billID", -1); 
        System.out.println("Getting bill ID from pending bill activity " + billID);   
        
        // Setup input
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        String username = settings.getString("username", "DEFAULT");
        Map<String, Object> input = new HashMap<String, Object>(); 
        input.put("username", username); 
        input.put("action",  "view.do");  
        input.put("billID", billID);   
        
        // Get output
        Map<String, Object> output;  
        Map<String, Object> billList = null; 
        try {
        	output = MySocket.runSocket(input); 
        	billList = (Map<String, Object>) output.get("bill"); 
        	List<String> errors = (List<String>) output.get("errors");
    	    if (errors.size()!=0) {
    	    	for(String errorStr : errors) {
    	    		System.out.println("Type of error in paybillactivity " + errorStr); 
    	    	}
    	    	Intent toError = new Intent(PayBillActivity.this, ErrorActivity.class); 
    	    	toError.putStringArrayListExtra("errorlist", new ArrayList<String>(errors)); 
    	    	startActivity(toError); 
    	    }
        } catch (UnknownHostException e) {
			System.out.println("UnknownHostException");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("IOException");
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.out.println("ClassNotFoundException");
			e.printStackTrace();
		}

        // Putting view bill data onto output
        TextView description = (TextView) findViewById(R.id.description_value_PAYBILL);  
        description.setText((String)billList.get("description")); 
        TextView date = (TextView) findViewById(R.id.date_value_PAYBILL);  
        date.setText((String)billList.get("date")); 
        TextView totalAmount = (TextView) findViewById(R.id.total_amount_value_PAYBILL);  
        totalAmount.setText((String)billList.get("amount")); 
        TextView paidBy = (TextView) findViewById(R.id.paid_by_value_PAYBILL);  
        paidBy.setText((String)billList.get("paidBy")); 
        TextView location = (TextView) findViewById(R.id.location_value_PAYBILL);  
        location.setText((String)billList.get("location")); 
        
        TableLayout debtorsTable = (TableLayout) findViewById(R.id.debtors_table_PAYBILL); 
        List<ArrayList<Object>> payList = (List<ArrayList<Object>>)billList.get("list"); 
        boolean pay = false; 
        for(ArrayList<Object> user : payList) {      
        	String nameStr = (String) user.get(1);   
        	String amountStr = ((Double) user.get(2)).toString(); 
        	String billStateStr = (String) user.get(3); 
        	String actionStr = (String) user.get(4);  
        	System.out.println("action string " + actionStr);    
        	if(actionStr != null && !actionStr.equals(""))  
        		pay = true; 
        	
        	TextView name = new TextView(this);  
        	name.setText(nameStr); 
        	TextView amount = new TextView(this);  
        	amount.setText(amountStr); 
        	TextView billState = new TextView(this);  
        	billState.setText(billStateStr); 
            TableRow tr = new TableRow(this);   
            tr.setLayoutParams(new LayoutParams(
                    LayoutParams.FILL_PARENT,  
                    LayoutParams.WRAP_CONTENT)); 
            tr.addView(name);   
            tr.addView(amount);   
            tr.addView(billState);   
            debtorsTable.addView(tr);  
        }

        // Set payment info to invisible if necessary
        if(!pay) {
        	TableLayout paymentTable = (TableLayout) findViewById(R.id.payment_info_table_PAYBILL);  
        	TextView paymentLabel = (TextView) findViewById(R.id.payment_info_label_PAYBILL);     
        	paymentTable.setVisibility(4); 
        	paymentLabel.setVisibility(4); 
        }
        // Pay bill
        else {
        	Button payButton = (Button) findViewById(R.id.pay_btn_PAYBILL); 
        	payButton.setId(billID); 
        	payButton.setOnClickListener(
    	    		new View.OnClickListener() {
    	    	    	public void onClick(View v) {
    	    	    		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    	    	            String username = settings.getString("username", "DEFAULT");
    	    	            Map<String, Object> input = new HashMap<String, Object>(); 
    	    	            input.put("username", username); 
    	    	            input.put("action",  "pay.do");  
    	    	            int billID = v.getId(); 
    	    	            input.put("billID", billID);   
    	    	            Map<String, Object> output;  
    	    	            try {
    	    	            	output = MySocket.runSocket(input); 
    	    	            	List<String> errors = (List<String>) output.get("errors");
    	    	        	    if (errors.size()!=0) {
    	    	        	    	Intent toError = new Intent(PayBillActivity.this, ErrorActivity.class); 
    	    	        	    	toError.putStringArrayListExtra("errorlist", new ArrayList<String>(errors)); 
    	    	        	    	startActivity(toError); 
    	    	        	    } else {
    	    	        	    	startActivity(new Intent(PayBillActivity.this, ClosedBillsActivity.class));   
    	    	        	    }
    	    	            } catch (UnknownHostException e) {
    	    	    			System.out.println("UnknownHostException");
    	    	    			e.printStackTrace();
    	    	    		} catch (IOException e) {
    	    	    			System.out.println("IOException");
    	    	    			e.printStackTrace();
    	    	    		} catch (ClassNotFoundException e) {
    	    	    			System.out.println("ClassNotFoundException");
    	    	    			e.printStackTrace();
    	    	    		}
    	    	    	}
    	    		});    
		
        	
        }
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.pay_bill, menu); 
        return true; 
    }
}
